package cc.lucien.thread;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Demo02 {
    /**
     * 通过多线程并发，同时完成三个文件的复制（上传）操作
     * 步骤：
     *  1.准备一个容器，存储要复制的文件对象
     *  2.创建线程类对象，并完成核心功能的编写（文件的复制)
     *  3.开启三条线程同时复制
     */

    public static void main(String[] args) {
        List<File> list = new ArrayList<>();
        list.add(new File("F:/m1.mp3"));
        list.add(new File("F:/m2.mp3"));
        list.add(new File("F:/m3.mp3"));

        //复制文件
        for (File file : list) {
            new Thread(new CopyFile(file)).start();
        }
    }
}

class CopyFile implements Runnable{
    private File file;

    public CopyFile(File file) {
        this.file = file;
    }

    @Override
    public void run() {
        try {
            // 读文件
            InputStream inputStream = new FileInputStream(file);
            BufferedInputStream bi = new BufferedInputStream(inputStream);
            OutputStream outputStream = new FileOutputStream("F:/tmp/"+file.getName());
            BufferedOutputStream bo = new BufferedOutputStream(outputStream);
            byte[] bytes = new byte[1024 * 1024];

            //  边读边写

            int c;
            while ((c = bi.read(bytes,0,bytes.length)) != -1){
                Thread.currentThread().sleep(500);
                bo.write(bytes,0,c);
            }

            bo.flush();
            bo.close();
            outputStream.close();
            bi.close();
            inputStream.close();

            System.out.println("复制完成");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
